package com.leetcode.根据数据结构分类.数组;

import java.util.Arrays;

/**
 * @author: xiaomi
 * @date: 2021/1/17
 * @description: 5243. 同积元组
 * https://leetcode-cn.com/contest/weekly-contest-224/problems/tuple-with-same-product/
 */
public class B_5243_同积元组 {

    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 4, 5, 10};
        nums = new int[]{2, 3, 4, 6, 8, 12};
        B_5243_同积元组 action = new B_5243_同积元组();
        int res = action.tupleSameProduct(nums);
        System.out.println("res = " + res);
    }

    /**
     * 1.找到不同的组合
     * 如果直接找就太慢了。那么只能先通过排序。
     *
     * @param nums
     * @return
     */
    public int tupleSameProduct(int[] nums) {
        int len = nums.length;
        if (len < 4) {
            return 0;
        }

        int i = 0, j = len - 1, k = 1, l = j - 1;
        //1.先进行排序
        Arrays.sort(nums);
        int value = 0;
        //保存乘积
        int tempValue = 0;
        int count = 0;

        while (k < l) {

            while (k < l) {
                value = nums[i] * nums[j];
                while (k < l) {
                    tempValue = nums[k] * nums[l];
                    if (value == tempValue) {
                        count++;
                        k++;
                        l--;
                    } else if (value > tempValue) {
                        k++;
                    } else {
                        l--;
                    }
                }
                //一遍循环结束
                j--;
                l = j - 1;

                //复原K
                k = i + 1;
            }
            i++;
            k = i + 1;

            j = len - 1;
            l = j - 1;
        }

        return count * 8;
    }
}
